use std::sync::{Arc, LockResult, Mutex};
use std::thread;

fn main() {
    //创建一个共享的可变整数
    let counter = Arc::new(Mutex::new(0));
    //创建一个多线程增加计数器
    let mut handles = vec![];

    for _ in 0..5 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            //获取锁
            let result: LockResult<_> = counter.lock();
            //尝试获取锁，如果失败就打印
            match result {
                Ok(mut num) => {
                    *num += 1;
                    // panic
                    if *num == 3 {
                        panic!("Simulated panic!");
                    }
                }
                Err(poisoned) => {
                    // "poisoned"
                    println!("Thread encountered a poisoned lock: {:?}", poisoned);
                    // MutexGuard
                    let mut num = poisoned.into_inner();
                    *num += 1;
                }
            }
        });
        handles.push(handle);
    }
    //
    for handle in handles {
        handle.join().unwrap();
    }
    //
    println!("Final count: {}", *counter.lock().unwrap());
}
